﻿using System;
using System.Threading.Tasks;
using System.Windows;
using WPFServices.Commands;
using WPFServices.Models.Domain;
using WPFServices.Services.DomainService.Role;

namespace WPFServices.ViewModels.DomainViewModel
{
    public class EditRoleViewModel : BaseViewModel
    {
        private readonly RoleService _roleService;
        private int _roleId;
        private string _roleName = string.Empty;
        private string _roleCode = string.Empty;
        private string _description = string.Empty;
        private bool _isEnabled = true;

        public EditRoleViewModel(RoleDto role)
        {
            _roleService = new RoleService();

            // 初始化数据
            _roleId = role.Id;
            RoleName = role.RoleName;
            Description = role.Description ?? string.Empty;

            SaveCommand = new RelayCommand(async _ => await SaveRoleAsync(), _ => CanSave());
            CancelCommand = new RelayCommand(_ => Cancel());
        }

        public event Action<bool> CloseWindow;

        #region 属性
        public string RoleName
        {
            get => _roleName;
            set => SetProperty(ref _roleName, value);
        }

        public string Description
        {
            get => _description;
            set => SetProperty(ref _description, value);
        }
        #endregion

        #region 命令
        public RelayCommand SaveCommand { get; }
        public RelayCommand CancelCommand { get; }
        #endregion

        #region 方法
        private bool CanSave()
        {
            return !string.IsNullOrWhiteSpace(RoleName);
        }

        private async Task SaveRoleAsync()
        {
            try
            {
                var updateDto = new CreateUpdateRoleDto
                {
                    RoleName = RoleName.Trim(),
                    Description = Description?.Trim()
                };

                await _roleService.UpdateRoleAsync(_roleId, updateDto);

                MessageBox.Show("角色更新成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                CloseWindow?.Invoke(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"更新角色失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void Cancel()
        {
            CloseWindow?.Invoke(false);
        }
        #endregion
    }
}